<?php

declare(strict_types=1);

namespace App\Chat\Controller\Talk;

use App\Chat\Annotation\ChatAuth;
use App\Chat\Constant\TalkModeConstant;
use App\Chat\Controller\ChatBaseController;
use App\Chat\Service\GroupMemberService;
use App\Chat\Service\TalkService;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\PostMapping;

#[Controller('ch/chat/record'),ChatAuth]
class RecordController extends ChatBaseController
{
    #[Inject]
    protected TalkService $talkService;

    /**
     * 获取对话面板中的聊天记录
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    #[PostMapping('list')]
    public function records(): \Psr\Http\Message\ResponseInterface
    {
        $params = $this->request->inputs(['talk_type','robot_id', 'receiver_id', 'record_id']);

        $this->validate($params, [
            'talk_type'   => 'required|in:1,2',
            'robot_id'    => 'required',
            'receiver_id' => 'required|integer|min:1',
        ]);


        $limit  = 30;
        $result = $this->talkService->getChatRecords(
            intval($params['robot_id']),
            $params['receiver_id'],
            intval($params['talk_type']),
            intval($params['record_id']),
            $limit
        );

        return $this->success([
            'rows'      => $result,
            'record_id' => $result ? array_shift($result)['id'] : 0,
            'limit'     => $limit
        ]);
    }

    /**
     * 聊天记录
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    #[PostMapping('history')]
    public function history(): \Psr\Http\Message\ResponseInterface
    {
        $params = $this->request->inputs(['talk_type','robot_id', 'receiver_id', 'record_id','msg_type','keyword']);

        $this->validate($params, [
            'talk_type'   => 'required|in:1,2',
            'robot_id'    => 'required',
            'receiver_id' => 'required|integer|min:1',
        ]);

        $msgType = !empty($params['msg_type']) ?  json_decode($params['msg_type'],true) : [];
        $keyword = $params['keyword'] ?? '';

        $limit  = 30;
        $result = $this->talkService->getChatRecords(
            intval($params['robot_id']),
            $params['receiver_id'],
            intval($params['talk_type']),
            intval($params['record_id']),
            $limit,
            $msgType,
            $keyword
        );

        return $this->success([
            'rows'      => $result,
            'record_id' => $result ? array_shift($result)['id'] : 0,
            'limit'     => $limit
        ]);
    }
}